//
//  MovieDetailViewController.m
//  豆瓣终极版
//
//  Created by dllo on 15/12/18.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "MovieDetailViewController.h"
#import "MovieDetailView.h"
#import "AppTools.h"
#import "MovieDetail.h"
#import "DataBaseSingleton.h"
#import "LandPageViewController.h"
#import "UserListViewController.h"
@interface MovieDetailViewController ()

@property (nonatomic, retain) MovieDetailView *movieDetailView;
@property (nonatomic, retain) MovieDetail *movieDetail;
@end

@implementation MovieDetailViewController

- (void)dealloc{
    [_movieDetailView release];
    [super dealloc];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = self.movieTitle;
    
    // 返回列表按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_nav_back@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(returnBtnAction:)];
    
    // 收藏按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_nav_share@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(collectBtnAction:)];
    
    // 把封装的MovieDetailView放到controller上
    self.movieDetailView = [[MovieDetailView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.movieDetailView];
    
    // 断网缓存
    
    NSString *filePath = [AppTools createFilePathFromDocumentWithFolders:@[@"Movie", @"MovieDetail"] fileName:self.movieId];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        NSMutableDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary *dic = [bigDic objectForKey:@"result"];

        MovieDetail *movieDetail = [[MovieDetail alloc] init];
        [movieDetail setValuesForKeysWithDictionary:dic];
        self.movieDetailView.moviedetail = movieDetail;
        
        [movieDetail release];
        NSLog(@"从本地获取电影详情");
    } else {
        NSLog(@"从网络获取电影详情");
        // 使用AFN解析电影详情数据
        NSString *str = @"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/searchmovie.php?movieId=";
        NSString *url = [str stringByAppendingString:self.movieId];
        //    NSLog(@"=========%@", url);
        [AppTools getDataWithAFNUrl:url block:^(id result) {
            
            NSMutableDictionary *bigDic = result;
            NSMutableDictionary *dic = [bigDic objectForKey:@"result"];
            self.movieDetail = [[MovieDetail alloc] init];
            [self.movieDetail setValuesForKeysWithDictionary:dic];
            self.movieDetailView.moviedetail = self.movieDetail;
            
            UserListViewController *userListVC = [[UserListViewController alloc] init];
            userListVC.movieId = self.movieId;
            
            NSData *data = [NSJSONSerialization dataWithJSONObject:result options:NSJSONWritingPrettyPrinted error:nil];
            [data writeToFile:filePath atomically:YES];
            
            
        } errorBlock:^(NSError *error) {
            
            
        }];

    }
    
    
    
    
    
    
    
}
// 点击返回按钮触发事件
- (void)returnBtnAction:(UIBarButtonItem *)btn{
    // pop回电影列表
    [self.navigationController popViewControllerAnimated:YES];
    
}
// 点击收藏按钮触发事件
- (void)collectBtnAction:(UIBarButtonItem *)btn{
    BOOL flag = NO;
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"state"] isEqualToString:@"YES"]) {
        // 1.先查询是否收藏过
        NSMutableArray *array = [[DataBaseSingleton shareDataBase] selectMovieTable];
        for (Movie *movie in array) {
            if ([self.movieId isEqualToString:movie.movieId]) {
                flag = YES;
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"该电影已经被收藏过" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *alertAct = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    
                }];
                [alertC addAction:alertAct];
                [self presentViewController:alertC animated:YES completion:^{
                    
                    
                }];
                
            }
        }
        if (flag == NO){
                Movie *movie = [[Movie alloc] init];
                movie.movieId = self.movieId;
                movie.movieName = self.movieDetail.title;
                movie.pic_url = self.movieDetail.poster;
                [[DataBaseSingleton shareDataBase] insertMovieInToTable:movie];
                NSLog(@"movie == %@", movie.movieName);
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:alertC animated:YES completion:^{
                    
             }];
            [self dismissViewControllerAnimated:YES completion:^{
                
                
            }];


            
            }
        
        
        
        
    } else {
        // 模态到登陆界面
        LandPageViewController *landPageVC = [[LandPageViewController alloc] init];
        UINavigationController *naC = [[UINavigationController alloc] initWithRootViewController:landPageVC];
        
        [self presentViewController:naC animated:YES completion:^{
            
            
        }];
        
        
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
